<template>
  <div class="login-container">
    <div class="header">
      <div class="container">
        <span class="logo"></span>
      </div>
    </div>
    <div class="login-body">
      <div class="login-box">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="demo-ruleForm">
          <el-form-item label=" " prop="username">
            <el-input
              type="text"
              v-model="ruleForm.username"
              autocomplete="off"
              placeholder="请输入用户名"
            >
              <i slot="prefix" class="login-icon user-icon"></i>
            </el-input>
          </el-form-item>
          <el-form-item label=" " prop="password">
            <el-input
              type="password"
              v-model="ruleForm.password"
              autocomplete="off"
              @keyup.enter.native="submitForm('ruleForm')"
              placeholder="请输入密码"
            >
              <i slot="prefix" class="login-icon pass-icon"></i>
            </el-input>
          </el-form-item>
          <el-form-item v-if="needCode" class="code" label=" " prop="code">
            <el-input
              type="text"
              v-model="ruleForm.code"
              autocomplete="off"
              @keyup.enter.native="submitForm('ruleForm')"
              placeholder="请输入验证码"
            >
              <i slot="prefix" class="login-icon code-icon"></i>
            </el-input>
            <span title="点击获取验证码" class="codeImg" @click="getVerifyCode">
              <img :src="verCode" alt />
            </span>
            <div v-if="warnTextShow" class="warnText">验证码已失效，请更新验证码!</div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
              :disabled="isDisabled"
            >{{btnName}}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="login-footer">
      <div class="version">
        <div class="version-item">Insight DataSpace V1.6.0</div>
        <div class="version-item">技术支持： 浪潮信息</div>
        <div class="version-item">版权信息： Copyright &copy; 2019 Inspur</div>
      </div>
    </div>
  </div>
</template>
<script>
import { globalApi } from "@/request";
import { SET_LOGINER_INFO_AND_INSTALLED_SERVICES, SET_MODIFY_DAY } from "@/store/action-types";
import { mapState } from "vuex";
import { userNavList } from '@/layout/navListMap'
import { MANAGER_ROLE_CODE, USER_ROLE_CODE, SUCCESS_CODE } from "@/const";


export default {
  data() {
    return {
      isDisabled: false,
      warnTextShow: false, //验证码30分钟超时提醒
      btnName: "登 录",
      ruleForm: {
        username: "",
        password: "",
        code: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入登录账号！", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入登录密码！", trigger: "blur" }
        ],
        code: [
          { required: true, message: "请输入验证码！", trigger: "blur" },
          { min: 4, max: 4, message: "长度为4位的字符", trigger: "blur" }
        ]
      },
      verCode: "",
      needCode: false,
      href:window.location.href,
      issso:false
    };
  },
  computed: {
    ...mapState(["loginerRole"])
  },
  mounted() {
    this.issso = /validator/.test(this.href);
    if(this.issso){
      this.handleLogin()
    } else {
      this.handleLogin({ignoreError: 1})
    }
  },
  methods: {
    getIsNeedCode() {
      globalApi.isNeedCode().then(res => {
        if (res.data.need) {
          this.needCode = true;
          this.getVerifyCode();
        } else {
          this.needCode = false;
        }
      });
    },
    getVerifyCode() {
      this.warnTextShow = false;
      globalApi.getCode().then(res => {
        this.verCode = " data:image/png;base64," + res.data.result;
        window.codeRefrsh?clearTimeout(codeRefrsh):'';
        window.codeRefrsh = setTimeout(() => {
          this.warnTextShow = true
        },30*60*1000);
      });
    },
    utf8ToB64(stringToEncode) {
      return window.btoa(unescape(encodeURIComponent(stringToEncode)));
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.btnName = "正在登录中...";
          this.isDisabled = true;
          let user = this.ruleForm.username + ":" + this.ruleForm.password;
          user = "Basic " + this.utf8ToB64(user);
          // user, this.ruleForm.code
          this.handleLogin({user, code: this.ruleForm.code})
        }
      });
    },
    // 登录操作
    async handleLogin(info) {
      try {
        let res = '';
        if(this.issso){
          res = await globalApi.loginsso(window.location.hash.split('?')[1])
        }else{
          res = await globalApi.login(info)
        }
        const loginerRole = res.data.role;
        const loginerUserId = res.data.id;
        const loginerName = res.data.username;
        const installedServices = res.data.resourceList;
        // 密码安全基线
        const modifyPass = res.data.modifyPass ? '1' : ''; // admin是否需要修改密码（true-需要修改）
        const modifyDay = res.data.modifyDay; // 还有多少天需要修改密码（-1表示admin）
        await this.$store.dispatch(SET_MODIFY_DAY, modifyDay);
        const data = {
          loginerName,
          loginerRole,
          loginerUserId,
          installedServices,
          modifyPass
        };
        await this.$store.dispatch(
          SET_LOGINER_INFO_AND_INSTALLED_SERVICES,
          data
        )
        const storage = window.localStorage;
        storage.setItem("lastLoginerName", loginerName);
        storage.setItem("lastRole", loginerRole);
        storage.setItem("lastUserId", loginerUserId);
        storage.setItem("lastModifyDay", modifyDay);
        storage.setItem("lastModifyPass", modifyPass); // 初次修改密码后，将其清除
        storage.setItem("needShownModifyDay", '1'); // 本次登录是否提示 过期日期
        storage.setItem(
          "lastInstalledServices",
          JSON.stringify(installedServices)
        );
        if (loginerRole !== USER_ROLE_CODE) {
          if (modifyPass && loginerRole === MANAGER_ROLE_CODE) { // admin初次登录，强制修改密码
            this.pushRoute("/changePassword")
          } else {
            this.pushRoute("/home")
          }
        } else {
          // 顺序跟后端协调？
          const upperCaseInstalledServices = installedServices.map(m => m.toUpperCase());
          const firstUserNav = userNavList.find( nav => upperCaseInstalledServices.includes(nav.title.toUpperCase()) ) || {title: upperCaseInstalledServices[0]}
          console.log('firstUserNav.title', firstUserNav.title);
          this.pushRoute("/" + firstUserNav.title)
        }
      } catch (err) {
        this.btnName = "登 录";
        this.isDisabled = false;
        this.getIsNeedCode()
      }
    },
    pushRoute(route) {
      this.$router.push(route)
    }
  }
};
</script>
<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100vh;
  min-height: 800px;
  background: url("~@/assets/image/login-banner2.png") 0 0 no-repeat;
  background-size: cover;
  position: relative;
  // background-position: top 0px right 0px;
  // background-attachment: fixed;
  .header > .container {
    width: 100%;
    height: 100%;
    margin: 0 auto;
    position: relative;
    padding-top: 20px;
    .logo {
      width: 200px;
      height: 63px;
      display: block;
      background: url("~@/assets/image/login-logo1.png") no-repeat 0 center;
      margin-left: 60px;
    }
  }
  .login-body {
    height: calc(100% - 83px);
    min-height: 650px;
    min-width: 1100px;
    width: 100%;
    .login-box {
      width: 326px;
      position: absolute;
      top: 20%;
      left: 60px;
      background: #ffffff;
      box-shadow: 0 2px 36px 0 rgba(0, 0, 0, 0.12);
      border-radius: 18px;
      form {
        overflow: hidden;
        padding: 63px 25px 23px 25px;
        .code {
          .el-input {
            width: 200px;
          }
        }
        .codeImg {
          display: inline-block;
          width: 60px;
          height: 28px;
          vertical-align: middle;
          cursor: pointer;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .el-form-item__content {
          height: 45px;
        }
        button {
          width: 100%;
          // height: 50px;
        }
        input {
          padding-left: 45px;
        }
        .login-icon {
          display: block;
          width: 32px;
          height: 32px;
          margin-top: 4px;
          position: relative;
          background: url("~@/assets/image/login-icons.png") no-repeat;
        }
        .code-icon::after,
        .user-icon::after {
          content: "";
          width: 1px;
          height: 100%;
          display: inline-block;
          position: absolute;
          right: 0;
          background: url("~@/assets/image/login-icons.png") no-repeat right;
        }
        .pass-icon {
          background: url("~@/assets/image/login-icons.png") no-repeat right;
        }
        .code-icon {
          background: url("~@/assets/image/code.png") no-repeat center;
          background-size: 24px;
        }
      }
    }
  }
  .login-footer {
    width: auto;
    position: absolute;
    right: 60px;
    bottom: 40px;
    .version {
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
      align-items: center;
      font-size: 14px;
      color: #409eff;
    }
  }
}
@media (min-width: 1920px) {
  .login-container {
    .login-body {
      .login-box {
        width: 430px;
        left: 200px;
        form {
          padding: 63px 25px 23px 25px;
          button {
            margin-top: 40px;
          }
          .code .el-input {
            width: 300px;
            position: relative;
          }
          .el-form-item {
            margin-bottom: 40px;
          }
          .warnText{
            color: #F56C6C;
            font-size: 12px;
            position: absolute;

          }
        }
      }
    }
    .login-footer {
      .version {
        color: #409eff;
        font-size: 14px;
      }
    }
  }
}
</style>
<style>
.login-container form label {
  display: none;
}
.login-container form input.el-input__inner {
  padding-left: 45px;
}
</style>